<script lang="ts" setup>
import { ref } from "vue";
import { storeToRefs } from 'pinia/dist/pinia'
import { useBasicStore } from '../../store/basic'
import { ElMessage, ElMessageBox } from 'element-plus'
import { importsExcel } from '@/utils/excel'
import { aoaToSheetXlsx } from '@/utils/excel'
import axiosReq from '@/utils/axios-req'
import { AxiosResponse } from 'axios'
import { useI18n } from 'vue-i18n';


interface Equipment {
    id: number
    name: string
    state: '空闲' | '占用' | '故障' | '报废'
    category_id: number
    category_name: string
    address: string,
    department_id: string,
    department_name: string,
    leader_name: string
}

type EquipmentResponse = AxiosResponse<{
    link: {
        next: string,
        previous: string
    },
    count: number,
    results: Equipment[]
}>

type EditForm = {
    department: "学工部" | "后勤部" | "网信部" | "宣传部" | "行政部" | null,
    category: "家具" | "电子设备" | "通信设备" | "办公设备" | null,
    name: string | null,
    place: string | null
}

const borrowerVisible = ref(false)
const repairVisible = ref(false)
const editVisible = ref(false)
const equipmentId = ref(0)

const { userInfo } = storeToRefs(useBasicStore())
const { username } = userInfo.value

const equipmentIdSelection = ref<number[]>([])

const uploadState = reactive({
    loading: false,
    headers: '' as any,
    listData: [] as any[]
})

const { t } = useI18n();

const handleSelectionChange = (val: Equipment[]) => {
    equipmentIdSelection.value = val.map(equip => equip.id)
}

const changeEditForm = async (form: EditForm) => {
    const res: AxiosResponse<{
        data: Equipment[]
    }> = await axiosReq({
        url: '/equipments/update_equipment_batch/',
        method: 'put',
        data: {
            editForm: form,
            equipmentIdSelection: equipmentIdSelection.value
        }
    })
    console.log(res.data)
}

const changeBorrowerVisible = (visible: boolean) => {
    borrowerVisible.value = visible
}

const changeRepairVisible = (visible: boolean) => {
    repairVisible.value = visible
}

const changeEditVisible = (visible: boolean) => {
    editVisible.value = visible
}

const borrowerClick = (equipmentId_: number, dialog_visible: boolean) => {
    borrowerVisible.value = dialog_visible
    equipmentId.value = equipmentId_
}

const repairClick = (equipmentId_: number, visible: boolean) => {
    repairVisible.value = visible
    equipmentId.value = equipmentId_
}

const filterDepartment = (value: string, row: Equipment) => {
    return row.department_name === value
}

const filterCategory = (value: string, row: Equipment) => {
    return row.category_name === value
}

const filterState = (value: string, row: Equipment) => {
    return row.state === value
}

const tableData = ref<Equipment[]>([])
const currentPage = ref(1)
const currentSize = ref(10)
const totalCount = ref(0)
onMounted(() => {
    fetchData(currentPage.value, currentSize.value)
})

const fetchData = async (page_num: number, size_num: number) => {
    try {
        const res: EquipmentResponse = await axiosReq({
            url: '/equipments/equipment_overview/',
            method: 'get',
            params: {
                page: page_num,
                size: size_num
            }
        })
        totalCount.value = res.data.count
        tableData.value = res.data.results
        console.log(tableData.value)
    } catch (error) {
        console.log(error)
    }
}

watch(currentPage, async (newVal) => {
    await fetchData(newVal, currentSize.value)
})

const uploadExcel = (uploadFile) => {
    uploadState.loading = true
    importsExcel(uploadFile)
        .then((res) => {
            uploadState.listData = res.tableData
            uploadState.headers = res.headers
            uploadState.loading = false
            console.log(res.tableData)

            const r = res.tableData.map((row) => {
                return Object.fromEntries(Object.entries(row).map(([key, value]) => {
                    return [t(key), value]
                }))
            })
            console.log(r)

            // tableData.value = r
        })
        .catch((err) => {
            console.log(err)
            uploadState.loading = false
        })
}

const exportExcel = async () => {
    const header = ['编号', '名称', '状态', '类别', '地点', '部门', '负责人']
    const data = tableData.value.map(equip => {
        return [equip.id, equip.name, equip.state, equip.category_name, equip.address, equip.department_name, equip.leader_name]
    })
    await aoaToSheetXlsx({ data, header, filename: '设备信息.xlsx', write2excelOpts: { bookType: 'xlsx' } })
}

const open = async () => {
    try {
        const message = await ElMessageBox.confirm(
            '数据将被删除，确定？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error',
            }
        )
        console.log(message)
        const res = await axiosReq({
            url: '/equipments/delete_equipment_batch/',
            method: 'delete',
            data: {
                equipmentIdSelection: equipmentIdSelection.value
            }
        })
        console.log(res)
        ElMessage({
            type: 'warning',
            message: '删除成功',
        })
    } catch (error) {
        ElMessage({
            type: 'success',
            message: '用户取消',
        })
    }
}
</script>

<template>
    <div>
        <div>
            <el-row>
                <el-col :offset="0" :span="2">
                    <el-button text type="primary" @click="editVisible = true">编辑</el-button>
                </el-col>
                <el-col :offset="0" :span="2">
                    <el-button text type="danger" @click="open">删除</el-button>
                </el-col>
                <el-col :offset="0" :span="2">
                    <el-upload ref="uploadRef" action="" multiple :on-change="uploadExcel" :auto-upload="false"
                        accept=".xls, .xlsx" :show-file-list="false">
                        <template #trigger>
                            <el-button text type="primary">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                上传excel
                            </el-button>
                        </template>
                    </el-upload>
                </el-col>
                <el-col :offset="0" :span="2">
                    <el-button text type="success" @click="exportExcel">
                        <el-icon>
                            <Download />
                        </el-icon>
                        下载excel
                    </el-button>
                </el-col>
            </el-row>
        </div>
        <el-pagination v-model:current-page="currentPage" :page-size="currentSize" :pager-count="7" hide-on-single-page
            layout="prev, pager, next" :total="totalCount" />
        <el-table :data="tableData" row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="编号" sortable width="80" />
            <el-table-column prop="name" label="名称" width="160" />
            <el-table-column prop="category_name" label="类别" width="160" filter-placement="bottom-end"
                :filter-method="filterCategory" :filters="[
                    { text: '家具', value: '家具' },
                    { text: '办公设备', value: '办公设备' },
                    { text: '电子设备', value: '电子设备' },
                    { text: '通信设备', value: '通信设备' }]" />
            <el-table-column prop="department_name" label="部门" width="120" filter-placement="bottom-end"
                :filter-method="filterDepartment" :filters="[
                    { text: '学工部', value: '学工部' },
                    { text: '后勤部', value: '后勤部' },
                    { text: '网信部', value: '网信部' },
                    { text: '宣传部', value: '宣传部' },
                    { text: '行政部', value: '行政部' }
                ]" />
            <el-table-column prop="leader_name" label="监督人" width="120" />
            <el-table-column prop="address" label="地点" width="160" />
            <el-table-column prop="state" label="状态" filter-placement="bottom-end" :filter-method="filterState"
                :filters="[
                    { text: '空闲', value: '空闲' },
                    { text: '占用', value: '占用' },
                    { text: '故障', value: '故障' },
                    { text: '报废', value: '报废' }]">
                <template #default="scope">
                    <el-tag :type="{
                    空闲: 'success',
                    占用: 'warning',
                    故障: 'danger',
                    报废: 'info'
                }[scope.row.state]" disable-transitions>
                        {{ {
                    空闲: '空闲',
                    占用: '占用',
                    故障: '故障',
                    报废: '报废'
                }[scope.row.state] }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="100">
                <template #default="scope">
                    <el-button text type="primary" v-if="scope.row.state === '空闲'"
                        @click="borrowerClick(scope.row.id, true)">
                        借用
                    </el-button>
                    <el-button text type="primary" v-if="scope.row.state === '占用'"
                        @click="repairClick(scope.row.id, true)">报修</el-button>
                    <el-button text type="primary" v-if="scope.row.state === '故障'" @click="">维修</el-button>
                    <el-button text type="primary" v-if="scope.row.state === '报废'" @click="">删除</el-button>
                </template>
            </el-table-column>

        </el-table>
        <BorrowDialog :equipmentId="equipmentId" :username="username" :dialog_visible="borrowerVisible"
            @update:dialog_visible="changeBorrowerVisible">
        </BorrowDialog>
        <RepairDialog :equipmentId="equipmentId" :username="username" :visible="repairVisible"
            @update:visible="changeRepairVisible">
        </RepairDialog>

        <EditDiaglog :dialog_visible="editVisible" @update:dialog_visible="changeEditVisible"
            @update:form="changeEditForm">
        </EditDiaglog>
    </div>
</template>
